package com.yeyks.commonReference.append.mattress.wechat.config;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.yeyks.common.em.pay.PayTypeEnum;
import com.yeyks.common.exception.ServiceException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 床垫微信服务工具对象
 */
@Component
@ConditionalOnBean({MattressWxProperties.class})
public class MattressWxConfigUtil {

    @Autowired
    private MattressWxProperties mattressWxProperties;

    //微信授权对象
    private WxMpService mattressWxMpService;
    //公众号默认付款对象
    private WxPayService mattressGzhWxPayService;

    public WxPayService getWxPayService(String type) {
        if (PayTypeEnum.GZH.desc().equals(type)) {
            return mattressGzhWxPayService;
//        } else if (PayTypeEnum.XCX.desc().equals(type)) {
//            return xcxWxPayService;
//        } else if (PayTypeEnum.WXPAY.desc().equals(type)) {
//            return appWxPayService;
        }
        throw new ServiceException("微信付款类型错误");
    }

    public WxMpService getMattressWxMpService() {
        return mattressWxMpService;
    }

    public WxPayService getMattressGzhWxPayService() {
        return mattressGzhWxPayService;
    }

    @PostConstruct
    public void init() {
        //初始化微信授权对象
        initWxMpService();
        //初始化微信付款对象
        initGzhWxPayService();
    }

    private void initWxMpService() {
        mattressWxMpService = new WxMpServiceImpl();
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(mattressWxProperties.getGzhAppId());
        config.setSecret(mattressWxProperties.getGzhSecret());
        mattressWxMpService.setWxMpConfigStorage(config);
    }

    private void initGzhWxPayService() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(mattressWxProperties.getGzhAppId()));
        payConfig.setMchId(StringUtils.trimToNull(mattressWxProperties.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(mattressWxProperties.getMchKey()));
        payConfig.setKeyPath(StringUtils.trimToNull(mattressWxProperties.getKeyPath()));
        mattressGzhWxPayService = new WxPayServiceImpl();
        mattressGzhWxPayService.setConfig(payConfig);
    }

}
